package com.telecom.util;

import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.util.Properties;

public class PropertiesFactory {
    private static final Properties PROPERTIES= new Properties();;
    private static final String CONFIG_FILE = "config.properties";

    static {
        try (InputStream inputStream = PropertiesFactory.class.getClassLoader().getResourceAsStream(CONFIG_FILE)) {
            if (inputStream == null) {
                throw new RuntimeException("配置文件不存在");
            }
            PROPERTIES.load(inputStream);
        } catch (Exception e) {
            throw new RuntimeException("加载配置文件失败");
        }
    }

    public static <T> T getBean(String key){
        String className = PROPERTIES.getProperty(key);//com.telecom.dao.impl.UserDaoJdbcImpl
        if (className == null || className.trim().isEmpty()) {
            throw new RuntimeException("配置中未找到对应的类名:"+key);
        }
        try {
            Class<T> clazz = (Class<T>) Class.forName(className);
            //获取构造方法，创建实例对象
            Constructor<T> constructor = clazz.getDeclaredConstructor();
            constructor.setAccessible(true);
            return constructor.newInstance();
        } catch (Exception e) {
            throw new RuntimeException("创建对象失败");
        }

    }

}
